﻿using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Linq;
using System.Configuration;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace BLL
{

    [DataServiceKey("PartitionKey", "RowKey")]
    public class tableanswers : TableServiceEntity
    {
        public string userid { get; set; }
        public int questionid { get; set; }
        public int optionid { get; set; }
        public bool iscorect { get; set; }
        public override string PartitionKey
        {
            get
            {
                return "a";
            }
            set { base.PartitionKey = value; }
        }
        public override string RowKey
        {
            get { return userid + questionid + optionid; }
            set { base.RowKey = value; }
        }
    }

    public class AnswersStorage
    {
        const string CONNECTION_STRING_SETTING_NAME = "DataConnectionString";
        const string TABLE_NAME = "answersquiztable4";
        public const string QUE_NAME = "razor-question-queue-cloud-place4";

        public static TableServiceContext GetContext()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((a, b) => b(ConfigurationManager.AppSettings[CONNECTION_STRING_SETTING_NAME]));
            var account = CloudStorageAccount.FromConfigurationSetting(CONNECTION_STRING_SETTING_NAME);
            var client = account.CreateCloudTableClient();
            client.CreateTableIfNotExist(TABLE_NAME);
            var context = client.GetDataServiceContext();

            return context;
        }

        public static void AddAnswer(tableanswers tableanswers)
        {
            var context = GetContext();
            var existsQuery = from e
                                in context.CreateQuery<tableanswers>(TABLE_NAME)
                              where
                              e.PartitionKey == tableanswers.PartitionKey
                              && e.RowKey == tableanswers.RowKey
                              select e;

            var existingObject = existsQuery.FirstOrDefault();

            if (existingObject == null)
            {
                context.AddObject(TABLE_NAME, tableanswers);
                context.SaveChanges();
            }
            else
            {
                existingObject.iscorect = tableanswers.iscorect;
                existingObject.optionid = tableanswers.optionid;
                existingObject.questionid = tableanswers.questionid;
                context.UpdateObject(existingObject);
            }
        }

        public static List<tableanswers> GetAllAnswers(string userID)
        {
            var context = GetContext();
            var answers = (context.CreateQuery<tableanswers>(TABLE_NAME).Where(customer => customer.userid == userID));
            return answers.ToList();
        }
    }
}
